import Validate from '/utils/validate';
import PageModel from '/utils/pagemodel';

let pagemodel = new PageModel();
let validateForm = new Validate();
const app = getApp();

Page({
  data: {
    carNum:``,
    showWarnTip: false,
    insuranceDateTip:'请选择车险有效期截止日期',
    enforceDateTip: '请选择交强险结束日期',
  },
  onLoad(query) {
    // 页面加载
    //获取并设置预约信息页面的数据
    this.setData({
      bookInfo: query,
    })
    //console.log(this.data.bookInfo.tel)
    // 初始化表单验证插件
    this.validateForm = new Validate({
      carNum:{
        required:true,
        carNumber:true,
      },
      insuranceDate:{
        required:true,
      },
      enforceDate:{
        required:true,
      }
    },{
      carNum:{
        required:`请正确填写您的车牌号码`,    
      },
      insuranceDate:{
        required:`请选择合规的车险有效日期`,
      },
      enforceDate:{
        required:`请选择有效的交强险日期`,
      }
    });
  },
  goToBookPage(){
    //转至预约信息页面
    my.navigateBack({
      delta: 1
    })
  },
  checkCarNum(e) {
    const carNum = e.detail.value;
    //console.log(e)
    if((carNum.length===6 || carNum.length===7) && (/^[A-Z]{1}[A-Z0-9]{5,6}$/.test(carNum))){ //车牌号码校验
      this.setData({
        carNum: e.detail.value,
      });
      return;
    }
    this.setData({
      'showWarnTip': true,
      'tipBanner': '请正确填写您的车牌号码',
      carNum: '',
    });
    var that = this;
    if(this.data.showWarnTip){
      tipCountDown(that,3);
    }
  },
  getTimeSelector(){   //车险有效日期选择器       
    var newDate = new Date();
    my.datePicker({ 
      currentDate: newDate.toLocaleString(), 
      startDate: "2017-01-01", 
      endDate: GetDateStr(365),
      success: (res) => {
        var result =  JSON.stringify(res.date); 
        var valDate = new Date(res.date);
        var date = new Date(res.date).format('Y\\年M\\月j\\日');
        //校验车检有效期是否距今三个月内
        if(valDate.getMonth()!= newDate.getMonth() && valDate.getMonth()!= newDate.getMonth()+1 && valDate.getMonth()!= newDate.getMonth()+2){
          this.setData({
            'showWarnTip': true,
            'tipBanner': '车检有效期不符合要求'
          })
          var that = this;
          if(this.data.showWarnTip){
            tipCountDown(that,3);
          }
          return;
        }
        this.setData({
          insuranceDate: date.toLocaleString(),
          insDate: res.date,
          insuranceDateTip:``
        });
      }, 
    }); 
  }, 
  getTimeSelector2(){   //交强险日期选择器       
    var newDate = new Date();
    
    my.datePicker({ 
      currentDate: newDate.toLocaleString(), 
      startDate: newDate.toLocaleString(), 
      endDate: GetDateStr(90), 
      success: (res) => {
        var result =  JSON.stringify(res.date); 
        var date = new Date(res.date).format('Y\\年M\\月j\\日');
        var valDate = new Date(res.date);
        //交强险到期时间须大于当前时间开始计算的半个月，即半个月内到期无法办理
        newDate.setDate(newDate.getDate()+15);
        if(valDate < newDate ){
          this.setData({
            'showWarnTip': true,
            'tipBanner': '交强险日期不符合要求'
          })
          var that = this;
          if(this.data.showWarnTip){
            tipCountDown(that,3);
          }
          return;
        }
        this.setData({
          enforceDate: date.toLocaleString(),
          enfDate: res.date,
          enforceDateTip:``
        });
      }, 
    }); 
  }, 
  onUnload() {
    // 关闭程序
  },
  onSubmit(e) {
    

    //表单字段校验(第一次提交)
    var dataSet = JSON.stringify(e.detail.value);
    //console.log(dataSet);
    if(!this.validateForm.checkForm(e)){
      const error = this.validateForm.errorList[0];
      this.setData({
        'showWarnTip': true,
        'tipBanner': error.msg
      })
      var that = this;
      if(this.data.showWarnTip){
        tipCountDown(that,3);
      }
      return;
    }
    //提交表单信息，导航至支付确认页面
    var car_num = '粤'+this.data.carNum;
    var car_state_time = this.data.insDate;
    var insurance_time = this.data.enfDate;
    var bookInfo = this.data.bookInfo;
    //console.log(app.userId)

    //验证是否重复提交表单，即用户在支付确认点击了上一步
    //若是则通过后台查询已经生成的订单
    //若返回并修改，则也要同步修改缓存数据并重新提交表单,并作废当前已提交到后台的订单信息；若返回但没有修改，则直接导航到支付确认页面
    let carInfo = my.getStorageSync({ key: "carInfo" }).data;
    if(carInfo!=null){
      if(carInfo.car_num===car_num && carInfo.car_state_time===car_state_time && carInfo.insurance_time===insurance_time){
        my.navigateTo({ 
            url: '../check-pay/check-pay',
        });
        return;
      }
    }

    my.httpRequest({
      url: app.orderSubmit_url,
      data:{
        // uid:---------------------------
        uid: app.userId,
        car_num: car_num,
        car_state_time:car_state_time,
        insurance_time:insurance_time,
        tel:bookInfo.tel,
        sms_code:bookInfo.sms_code,
        username:bookInfo.username,
        area:bookInfo.area,
        area_info:bookInfo.area_info,
        appointe_time:bookInfo.appointe_time,
      },
      method: 'POST',
      success: (res) => {
        //console.log('订单提交返回：')
        //console.log(res)
        my.setStorageSync({
          key: 'carInfo',
          data: {
            orderNo: res.data.data.order,
            total: res.data.data.order_amount,
            order_str: res.data.data.order_str,
            car_num: res.data.data.car_num,
            car_state_time: car_state_time,
            insurance_time: insurance_time,
          }
        });
        my.navigateTo({ 
          url: '../check-pay/check-pay',
        });
      },
      fail: function(res) {
        my.alert({
          content: '订单提交失败,请稍后再试',
        });
      },
      complete: function(res) {
        
      }
    });


    
  },
  

  
});

  

function add0(m){  
    return m<10?'0'+m : m;  
}  

//倒计时60s 间隔任务
function countDown(that,count) {
  if (count == 0) {
    that.setData({
      'vcode.disabled':false,
      'vcode.obj':'发送验证码',
    })
    return;
  }

  that.setData({
    'vcode.disabled':true,
    'vcode.obj': (count)+'秒后重发',
  })
  
  setTimeout(function(){
    count--;
    countDown(that, count);
  }, 1000);
}

//获取N天后的日期字符串
function GetDateStr(AddDayCount) {   
   var dd = new Date();  
   dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期  
   var y = dd.getFullYear();   
   var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取当前月份的日期，不足10补0  
   var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取当前几号，不足10补0  
   return y+"-"+m+"-"+d;   
} 


//倒计时3s 错误提示消失
function tipCountDown(that,count){
  if (count == 0) {
    that.setData({
      'showWarnTip':false,
    })
    return;
  }
  setTimeout(function(){
    count--;
    tipCountDown(that, count);
  }, 1000);
}


Date.prototype.format = function(format) {
    var returnStr = '';
    var replace = Date.replaceChars;
    for (var i = 0; i < format.length; i++) {       
        var curChar = format.charAt(i);         
        if (i - 1 >= 0 && format.charAt(i - 1) == "\\") {
            returnStr += curChar;
        }
        else if (replace[curChar]) {
            returnStr += replace[curChar].call(this);
        } else if (curChar != "\\"){
            returnStr += curChar;
        }
    }
    return returnStr;
};


Date.replaceChars = {
    shortMonthsNum: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
    shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],

    // Day
    d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
    D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
    j: function() { return this.getDate(); },
    l: function() { return Date.replaceChars.longDays[this.getDay()]; },
    N: function() { return this.getDay() + 1; },
    S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
    w: function() { return this.getDay(); },
    z: function() { var d = new Date(this.getFullYear(),0,1); return Math.ceil((this - d) / 86400000); }, // Fixed now
    // Week
    W: function() { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((((this - d) / 86400000) + d.getDay() + 1) / 7); }, // Fixed now
    // Month
    F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
    m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
    M: function() { return Date.replaceChars.shortMonthsNum[this.getMonth()]; },
    n: function() { return this.getMonth() + 1; },
    t: function() { var d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 0).getDate() }, // Fixed now, gets #days of date
    // Year
    L: function() { var year = this.getFullYear(); return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)); },   // Fixed now
    o: function() { var d  = new Date(this.valueOf());  d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear();}, //Fixed now
    Y: function() { return this.getFullYear(); },
    y: function() { return ('' + this.getFullYear()).substr(2); },
    // Time
    a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
    A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
    B: function() { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24); }, // Fixed now
    g: function() { return this.getHours() % 12 || 12; },
    G: function() { return this.getHours(); },
    h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
    H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
    i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
    s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
    u: function() { var m = this.getMilliseconds(); return (m < 10 ? '00' : (m < 100 ?
'0' : '')) + m; },
    // Timezone
    e: function() { return "Not Yet Supported"; },
    I: function() {
        var DST = null;
            for (var i = 0; i < 12; ++i) {
                    var d = new Date(this.getFullYear(), i, 1);
                    var offset = d.getTimezoneOffset();

                    if (DST === null) DST = offset;
                    else if (offset < DST) { DST = offset; break; }                     else if (offset > DST) break;
            }
            return (this.getTimezoneOffset() == DST) | 0;
        },
    O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
    P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':00'; }, // Fixed now
    T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
    Z: function() { return -this.getTimezoneOffset() * 60; },
    // Full Date/Time
    c: function() { return this.format("Y-m-d\\TH:i:sP"); }, // Fixed now
    r: function() { return this.toString(); },
    U: function() { return this.getTime() / 1000; }
};